//
//  AdController.m
//  HybidMediation
//
//  Created by jay Win on 2019/10/15.
//  Copyright © 2019 jay Win. All rights reserved.
//
#import "ADController.h"
@implementation ADController
+ (instancetype)instance{
    static ADController *manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [ADController new];
        
        [QQSdkAdsTool sharedInstance].delegate=manager;
        [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(sendAnalytics:) name:@"KKAnalyticsNot" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(sendReyunAtt:) name:@"KKReyunAttNot" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(iapCallBackAtt:) name:@"IapCallBackblock" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(sendAdsLoadListener:) name:@"KKAdsLoadListenerNot" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(sendAdsonUserDataListener:) name:@"KKAdsonUserDataListenerNot" object:nil];
        
        //获取uamessage
        [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(sendMessageToUnity:) name:@"QQSDKAfUaMessageNot" object:nil];
        //获取IPmessage
        [[NSNotificationCenter defaultCenter] addObserver:manager selector:@selector(sendIPMessageToUnity:) name:@"QQSDKAfIPMessageNot" object:nil];
        
    });
    return manager;
}

#pragma mark   广告控制器回调
- (void)onAdsListener:(nonnull NSString *)adsState {
    NSLog(@"----onAdsListener------");
     [self sendMessage:adsState];
}

- (void)onUserDataListener:(NSString *)jsonStr {
    [self sendUserData:jsonStr];
}

- (void)iapCallBackAtt:(NSNotification *)notification{
    NSDictionary * infoDic = [notification object];
    NSString *message = infoDic[@"jsonMessage"];
    [self sendCommType:@"IapCallback" AndMessage:message];
}
-(NSString *)convertToJsonStr:(NSDictionary *)dict{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}
- (void)sendUserData:(NSString *)message{
//    UnitySendMessage("SDKManager", "ImpressionCallback", [message UTF8String]);
    [self sendCommType:@"ImpressionCallback" AndMessage:message];
}

-(void)sendAnalytics:(NSNotification *)notification{
    NSDictionary * infoDic = [notification object];
    NSString *message = [self convertToJsonStr:infoDic];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       [self initAFCallBack:message];
       });
    
//    UnitySendMessage("SDKManager", "AnalyticsCallback", [[NSString stringWithFormat:@"%@",infoDic[@"network"]] UTF8String]);
}
-(void)initAFCallBack:(NSString *)message{
    NSLog(@"延迟执行:message == %@",message);
    [self sendCommType:@"AttributionObject" AndMessage:message];
}
-(void)sendReyunAtt:(NSNotification *)notification{
    NSDictionary * infoDic = [notification object];
//    UnitySendMessage("SDKManager", "ReyunAttributionCallback", [[NSString stringWithFormat:@"%@",infoDic[@"network"]] UTF8String]);
    NSString *message =[NSString stringWithFormat:@"%@",infoDic[@"network"]];
    
    [self sendCommType:@"ReyunAttributionCallback" AndMessage:message];
}

-(void)sendAdsLoadListener:(NSNotification *)notification{
    NSDictionary *dict = notification.userInfo;
    NSString *adsState = dict[@"adsState"];
    [self onAdsListener:adsState];
}
-(void)sendAdsonUserDataListener:(NSNotification *)notification{
    NSDictionary *dict = notification.userInfo;
    NSString *jsonStr = dict[@"jsonStr"];
    [self onUserDataListener:jsonStr];
}

-(void)sendMessageToUnity:(NSNotification *)notification{
    NSDictionary * infoDic = [notification object];
    NSString *jsonStr = infoDic[@"af_uaMessage"];
    [self sendCommType:@"AfUaMessageCallback" AndMessage:jsonStr];
}
-(void)sendIPMessageToUnity:(NSNotification *)notification{
    NSDictionary * infoDic = [notification object];
    NSString *jsonStr = infoDic[@"af_IPMessage"];
    [self sendCommType:@"AfIPMessageCallback" AndMessage:jsonStr];
}

- (void)sendMessage:(NSString *)message{
//    UnitySendMessage("SDKManager", "Callback", [message UTF8String]);
    [self sendCommType:@"Callback" AndMessage:message];
}

- (void)sendCommType:(NSString *)type AndMessage:(NSString *)message{
    NSLog(@"commMessage:type == %@;message == %@",type,message);
//    UnitySendMessage("SDKManager", "Callback", [message UTF8String]);
    NSDictionary *dict  = @{@"m":type,@"d":message};
    NSString *typeMessage = [self convertToJsonStr:dict];
    UnitySendMessage("SDKManager", "CommCallback", [typeMessage UTF8String]);
}


- (UIView *)getUnitySplashCustomView{
    UIView *unitySplashCustomView=nil;
    UIImage*splashLogoImage=[UIImage imageNamed:@"SplashLogoView.png"];
    if(splashLogoImage){
        unitySplashCustomView = [[UIView alloc] initWithFrame:CGRectMake(0.0, [UIScreen mainScreen].bounds.size.height-100.0, [UIScreen mainScreen].bounds.size.width, 100.0)];
        unitySplashCustomView.backgroundColor = [UIColor whiteColor];
        UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake((unitySplashCustomView.frame.size.width - 201.0)/2, 0.0, 201.0, unitySplashCustomView.frame.size.height)];
        logoImageView.image =splashLogoImage;
        logoImageView.contentMode = UIViewContentModeScaleAspectFit;
        [unitySplashCustomView addSubview:logoImageView];
    }
    return unitySplashCustomView;
}
-(BOOL)isDebugOrRelease{
    
#ifndef __OPTIMIZE__
    return 0;
 #else
    return 1;
#endif
}

-(void)setUnityLogLevel:(int)level{
    UnitySendMessage("SDKManager", "SetLogLevel",[[NSString stringWithFormat:@"%d",level] UTF8String]);
}

extern "C"{
    bool getGDPRStatus(){
        return [[QQSdkAdsTool sharedInstance]getGDPRStatus];
    }
    void init(){
        [[QQSdkAdsTool sharedInstance]initMediation];
    }
    void initMediation(){
        [[QQSdkAdsTool sharedInstance]initMediation];
    }
    void initAdsDisableAutoLoad(bool isAutoLoaded){
        [[QQSdkAdsTool sharedInstance]initAdsDisableAutoLoad:isAutoLoaded];
    }
    void loadSplash(){
        UIView *view=[[ADController instance]getUnitySplashCustomView];
        [[QQSdkAdsTool sharedInstance]loadSplash:UnityGetMainWindow() customView:view];
    }
    void showSplash(){
        [[QQSdkAdsTool sharedInstance]showSplash];
    }
    void showBanner(bool top){
        [[QQSdkAdsTool sharedInstance]showBanner:UnityGetGLViewController() bannerContainer:UnityGetGLViewController().view isTop:top];
    }
    void hideBanner(){
        [[QQSdkAdsTool sharedInstance] hideBanner];
    }
    bool hasInterstitial(){
        return [[QQSdkAdsTool sharedInstance] hasInterstitial];
    }
    void loadInterAds(){
        [[QQSdkAdsTool sharedInstance]loadInterAds];
    }
    void showInterstitial(){
        return [[QQSdkAdsTool sharedInstance]showInterstitial:UnityGetGLViewController()];
    }
    void showInterstitialWithScenes(char *scenes){
        return [[QQSdkAdsTool sharedInstance]showInterstitial:UnityGetGLViewController() WithScenes:[NSString stringWithUTF8String: scenes]];
    }
    bool hasRewardVideo(){
        return [[QQSdkAdsTool sharedInstance] hasRewardVideo];;
    }
    void loadRewardAds(){
        [[QQSdkAdsTool sharedInstance]loadRewardAds];
    }
    void showRewardVideo(){
        return [[QQSdkAdsTool sharedInstance]showRewardVideo:UnityGetGLViewController()];
    }
    void showRewardVideoWithScenes(char *scenes){
        return [[QQSdkAdsTool sharedInstance]showRewardVideo:UnityGetGLViewController() WithScenes:[NSString stringWithUTF8String: scenes]];
    }
    void showRewardVideoWithVerify(char *verify){
        return [[QQSdkAdsTool sharedInstance]showRewardVideo:UnityGetGLViewController() serverVerification:[NSString stringWithUTF8String: verify]];
    }
    void agreeGDPR(bool state){
        [[QQSdkAdsTool sharedInstance] agreeGDPR:state];
    }
    void agreeCOPPA(bool state){
         [[QQSdkAdsTool sharedInstance] agreeCOPPA:state];
    }
    char *getIDFA(){
        const char* result = [[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]UTF8String];
        char* templateChar = (char *)malloc(strlen(result) + 1);
        return strcpy(templateChar, result);
    }
    char *getRealCountry(){
        const char* result = [[[QQSdkAdsTool sharedInstance]getRealCountry]UTF8String];
        char* templateChar = (char *)malloc(strlen(result) + 1);
        return strcpy(templateChar, result);
    }
    void loadNative(double weight,double height){
        [[QQSdkAdsTool sharedInstance]loadNativeWeight:weight Height:height];
    }
    bool hasNative(){
        return [[QQSdkAdsTool sharedInstance]hasNative];
    }
    void showNative(double x,double y){
        [[QQSdkAdsTool sharedInstance] showNativeWithOriginX:x OriginY:y];
    }
    void hideNative(){
        [[QQSdkAdsTool sharedInstance]hideNative];
    }
    bool hasIntersPage(){
        return [[QQSdkAdsTool sharedInstance] hasIntersPage];
    }
    void showIntersPageWithScenes(char *scenes){
        [[QQSdkAdsTool sharedInstance]showIntersPage:UnityGetGLViewController() WithScenes:[NSString stringWithUTF8String: scenes]];
    }
    void setAdSoundEnable(bool isEnable){
        [[QQSdkAdsTool sharedInstance]setADVoice:isEnable];
    }
    void setTopOnChannel(char *channel){
        [[QQSdkAdsTool sharedInstance] setTopOnChannel:[NSString stringWithUTF8String:channel]];
    }
    
    void setTopOnSupChannel(char *channel){
        [[QQSdkAdsTool sharedInstance] setTopOnSupChannel:[NSString stringWithUTF8String:channel]];
    }
    bool DebugOrRelease(){
        return [[ADController instance]isDebugOrRelease];
    }
}
@end



